package gl.java.umsp.match;

import gl.java.umsp.bean.Room;
import gl.java.umsp.bean.User;
import gl.java.umsp.user.IUserRoomStateChangedListener;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 记录已经匹配成功的用户的房间信息
 */
@Slf4j
public class InRoomUserMap implements IUserRoomStateChangedListener {

    private Map<Integer, InRoomUser> userList = new ConcurrentHashMap<Integer, InRoomUser>();

    public InRoomUserMap() {
        MatchUserEventDispatcher.getInstance().add(this);
    }

    @Override
    public void onUserDisconnect(int userID) {
        log.info("user has disconnect ,remove the userID from InRoomUserMap" + userID);
        remove(userID);
    }

    @Override
    public void onUserLeave(int userID, String roomID) {
        remove(userID);
    }

    @Override
    public void onUserEnter(int userID, String roomID) {

    }

    private class InRoomUser {
        User user;
        Room room;

        InRoomUser(Room room, User user) {
            this.user = user;
            this.room = room;
        }
    }

    public void put(Room room, User user) {
        userList.put(user.userID, new InRoomUser(room, user));
    }

    public void remove(int userID) {
        InRoomUser remove = userList.remove(userID);
        if (remove != null) {
            Room room = remove.room;
            room.removeUserFromMatchedList(userID);
            log.info("remove the user " + userID + " from " + room);
        } else {
            log.warn("remove fail ,the user " + userID + "Not found the Room ");
        }
    }

    public Room isInMatching(int userID) {
        InRoomUser inRoomUser = userList.get(userID);
        return inRoomUser == null ? null : inRoomUser.room;
    }
}
